﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MayhemCore;
using System.Runtime.Serialization;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using System.ComponentModel;
using System.Threading;
using ComputerMayhem.Wpf;
using Microsoft.WindowsAPICodePack.ApplicationServices;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Forms;

namespace ComputerMayhem.Events
{

    [DataContract]
    [MayhemModule("Battery Level", "Monitors your battery level")]
    public class Battery : EventBase, IWpfConfigurable
    {
        private bool triggered = false;

        [DataMember]
        private int alertLevel;

        [DataMember]
        private bool greater;

        protected override void OnLoadDefaults()
        {
            alertLevel = 10;
            greater = false;
        }

        protected override void OnAfterLoad()
        {
            PowerManager.BatteryLifePercentChanged +=new EventHandler(PowerManager_BatteryLifePercentChanged);
        }

        void PowerManager_BatteryLifePercentChanged(object sender, EventArgs e)
        {
            int currentBatteryLife = PowerManager.BatteryLifePercent;
            bool trigger = greater ? (currentBatteryLife > alertLevel) : (currentBatteryLife < alertLevel);
            if (!triggered && trigger)
            {
                Trigger();
                triggered = true;
            }
            else if (!trigger)
            {
                ResetTrigger();
            }
        }

        protected override void OnDeleted()
        {
            PowerManager.BatteryLifePercentChanged -= new EventHandler(PowerManager_BatteryLifePercentChanged);
        }

        private void ResetTrigger()
        {
            triggered = false;
        }

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new BatteryConfig(alertLevel, greater);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            BatteryConfig config = configurationControl as BatteryConfig;
            alertLevel = config.BatteryLevelToMonitor;
            greater = config.Greater;

        }

        public string GetConfigString()
        {
            return "Battery level "+ (greater ? "above" : "below") + " " + alertLevel.ToString() + "%";
        }
    }
}
